package ch.ffhs.ks.mail;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.swing.SwingWorker;

import ch.ffhs.ks.model.Mail;
import ch.ffhs.ks.model.ModelContext;


public class MailDownloader extends SwingWorker<ArrayList<Mail>, Mail> {

	private ch.ffhs.ks.model.Folder folder;
	private ModelContext modelContext; 

	private int totalToDownload = 0;
	private int actualIndex = 0;

	public MailDownloader(ch.ffhs.ks.model.Folder folder, ModelContext modelContext)
	{
		this.folder = folder;
		this.modelContext = modelContext;
		this.modelContext.notifyProgress(folder.getName() + ": Beginne mit Synchronisation");
	}



	@Override
	protected ArrayList<Mail> doInBackground() throws Exception {

		ArrayList<Mail> mails = new ArrayList<Mail>();

		try {

			Properties props = System.getProperties();
			props.setProperty("mail.store.protocol", "imaps");

			Session session = Session.getDefaultInstance(props, null);

			Store store = session.getStore("imaps");

			store.connect(folder.getAccount().getImapAddress(), 
					folder.getAccount().getEmailAddress(), 
					folder.getAccount().getPassword());


			Folder f = store.getFolder(folder.toString());
			f.open(Folder.READ_WRITE);

			totalToDownload = 50;

			if(f.getMessageCount() < totalToDownload)
			{
				totalToDownload = f.getMessageCount();
			}

			Message me[] = f.getMessages();

			for (int i = me.length - 1; i >= me.length - 50; i--) {

				Message m = me[i];
				try{
					Mail mail = new Mail(m);

					if(!this.folder.getAccount().containsMail(mail))
					{
						mail.LoadContent(m);
						mails.add(mail);
						publish(mail);
					}

					actualIndex += 1;
				}
				catch(MessagingException ex)
				{
					ex.printStackTrace();
				}
			}

			f.close(true);
			store.close();
		} catch (MessagingException e) {
			e.printStackTrace();
		}

		return mails;
	}

	@Override
	protected void process(List<Mail> chunks) {
		for(Mail c : chunks)
		{
			if(c!= null)
			{
				folder.addMail(c);
			}
		}

		modelContext.updateEmailModel(folder);
		modelContext.notifyProgress(folder.getName() + ": Emails werden heruntergeladen ( "+actualIndex+" von "+totalToDownload+" ) ");

	}

	@Override
	protected void done() {
		folder.setLastUpdate(new Date());
		
		modelContext.mailDownloadCompleted(folder);
		modelContext.notifyProgress(folder.getName() + ": Alle Emails aktualisiert");

	}





}
